package tcp.socket.thread;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class CloseClient {
	private String host = "127.0.0.1";
	private int port = 9001;
	private Socket socket;
	
	public CloseClient() throws IOException{
		//socket = new Socket(host,port);
		//如果要限制建立连接的时间，需要使用无参构造
		socket = new Socket();
		SocketAddress address = new InetSocketAddress(host, port);
		socket.connect(address, 2000);
	}
	
	/**
	 * @param host
	 * @param port
	 * @throws IOException
	 */
	public CloseClient(String host,int port) throws IOException{
		this.host = host;
		this.port = port;
		socket = new Socket(host,port);
	}
	
	private PrintWriter getWriter(Socket socket) throws IOException{
		OutputStream os = socket.getOutputStream();
		return new PrintWriter(os);
	}
	
	private BufferedReader getReader(Socket socket) throws IOException{
		InputStream is = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(is));
	}
	
	public void talk(){
		try {
			BufferedReader br = getReader(socket);
			PrintWriter pw = getWriter(socket);
			pw.println("shutdown");
			pw.flush();
			String msg = null;
			while((msg = br.readLine()) != null){
				System.out.println(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) throws IOException {
		CloseClient client = new CloseClient();
		client.talk();
	}
}
